# -*- coding: utf-8 -*-

class DBConnect
  
  def initialize(host, user, pass, database)
    
    open(host, user, pass, database)
    
  end
  
  def open(host, user, pass, database)
    
    @db = Mysql.new(host, user, pass, database)
    begin
      @db.query("set names utf8")
    rescue
    end
  end
  
  def close()
    
    @db.close()
    
  end
  
  def query(sql)
    
    #print "#{sql}<br />"
    #output_log($logfile, "[#{Time.now}] #{sql}\n")
    return sql2array(sql)
    
  end
  
  def exec(sql)
    
    #print "#{sql}<br />"
    output_log($logfile, "[#{Time.now}] #{sql}\n")
    @db.query(sql)
    
  end
  
  def sql2array(sql)
    
    rs = @db.query(sql)
    
    fields = []
    i = 0
    
    fields = []
    i = 0
    
    rs.fetch_fields.each do |fd|
      fields[i] = fd.name
      i += 1
    end
    
    i = 0
    values = []
    
    rs.each do |row|
      
      val = {}
      j = 0
      
      fields.each do |fd|
        val[fd] = row[j]
        #print "#{row[j]}<br />"
        j += 1
      end
      
      values[i] = val
      i += 1
      
    end
    
    rs.free()
    
    return values
    
  end
  
  def list_fields(table)
    
    rs = @db.list_fields(table)
    #debug_print rs.num_fields()
    
    fields = []
    i = 0
    
    rs.fetch_fields.each do |fd|
      fields[i] = fd.name
      i += 1
    end
    
    rs.free()
    return fields
    
  end
  
  def escape_string(str)
    str = @db.escape_string(str.to_s)
    #print "#{str} => #{val}<br />"
    return str
    #return @db.quote(str)
  end
  
end
